package com.sec.android.app.myfiles.fragment.securefilelist;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.format.Formatter;
import android.util.TypedValue;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.altamirasoft.path_animation.PathLineAnimationView;
import com.sec.android.app.myfiles.R;
import com.sec.android.app.myfiles.activity.FolderSelectorBottomSheetActivity;
import com.sec.android.app.myfiles.facade.MyFilesFacade;
import com.sec.android.app.myfiles.facade.cmd.ToSelectModeCmd;
import com.sec.android.app.myfiles.feature.CloudMgr;
import com.sec.android.app.myfiles.feature.DragAndDropMgr;
import com.sec.android.app.myfiles.feature.MouseKeyboardMgr;
import com.sec.android.app.myfiles.feature.MultiWindowMgr;
import com.sec.android.app.myfiles.feature.ViEffectMgr;
import com.sec.android.app.myfiles.feature.layout.split.SplitLinearLayout;
import com.sec.android.app.myfiles.fragment.AbsMyFilesFragment;
import com.sec.android.app.myfiles.fragment.filelist.FileListAdapter;
import com.sec.android.app.myfiles.fragment.filelist.OnItemChangedListener;
import com.sec.android.app.myfiles.fragment.filelist.PathIndicator;
import com.sec.android.app.myfiles.info.AppConstants;
import com.sec.android.app.myfiles.info.AppFeatures;
import com.sec.android.app.myfiles.listener.DragAndDropReceiver;
import com.sec.android.app.myfiles.listener.ListenerMgr;
import com.sec.android.app.myfiles.listener.LocalBroadcastReceiver;
import com.sec.android.app.myfiles.listener.SystemBroadcastReceiver;
import com.sec.android.app.myfiles.listener.TimeSetBroadcastReceiver;
import com.sec.android.app.myfiles.log.Log;
import com.sec.android.app.myfiles.log.SamsungAnalyticsLog;
import com.sec.android.app.myfiles.module.ModuleLoader;
import com.sec.android.app.myfiles.module.abstraction.AbsReloadStrategyImp;
import com.sec.android.app.myfiles.module.abstraction.FileRecord;
import com.sec.android.app.myfiles.module.cloud.CloudFileRecord;
import com.sec.android.app.myfiles.module.local.file.LocalFileRecord;
import com.sec.android.app.myfiles.navigation.NavigationInfo;
import com.sec.android.app.myfiles.navigation.NavigationManager;
import com.sec.android.app.myfiles.util.BixbyUtil;
import com.sec.android.app.myfiles.util.FileUtils;
import com.sec.android.app.myfiles.util.StorageMonitor;
import com.sec.android.app.myfiles.util.UiUtils;
import com.sec.android.app.myfiles.widget.listview.AbsListViewImp;
import com.sec.android.app.myfiles.widget.listview.SelectionManager;

import java.util.ArrayList;

public class SecureFileListFragment extends AbsMyFilesFragment implements
        AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener, MultiWindowMgr.StateChangeListener,
        SystemBroadcastReceiver.OnMediaMounted, SystemBroadcastReceiver.OnMediaEject, SystemBroadcastReceiver.OnMediaScanStart, SystemBroadcastReceiver.OnMediaScanFinish, SystemBroadcastReceiver.OnMediaUnmounted,
        TimeSetBroadcastReceiver.OnTimeSetBroadcast, OnItemChangedListener, SplitLinearLayout.SplitBarPressedListener {

    private static final long SIZE_KILOBYTE = 1024;

    protected FileListAdapter mAdapter;
    protected AbsListViewImp mListViewImp;
    protected ListenerMgr mListenerMgr;
    private DragAndDropMgr mDragDrop;
    private AbsReloadStrategyImp mReloadStrategy;

    private MultiWindowMgr mMultiWindow;
    private OnItemChangedListener mOnItemChangedListener;

    private int mPreItemCnt = -1;
    private boolean mLoadingStatus = false;
    private boolean mNeedUpdateAfterLoading = false;
    private PathIndicator mPathIndicator;
    private TextView mCategorySizeView;
    protected View mClearHistoryButton;

    private static final String TAG = SecureFileListFragment.class.getSimpleName() + "-HYL";

    public SecureFileListFragment() {
        super();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.i(TAG, "onCreate");
        super.onCreate(savedInstanceState);
        mListenerMgr = new ListenerMgr();

        mListenerMgr.addListener(new SystemBroadcastReceiver(mContext, this, ListenerMgr.LifeCycle.CREATE, ListenerMgr.LifeCycle.DESTROY));
        mListenerMgr.addListener(new TimeSetBroadcastReceiver(mContext, this, ListenerMgr.LifeCycle.CREATE, ListenerMgr.LifeCycle.DESTROY));
        mListenerMgr.addListener(new LocalBroadcastReceiver(mContext, this, ListenerMgr.LifeCycle.CREATE, ListenerMgr.LifeCycle.DESTROY));
        mListenerMgr.notifyCreate();

        mReloadStrategy = ModuleLoader.getInstance().createReloadStrategy(mContext, getNavigationInfo());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //TODO SecureFileListFragment 有自己的UI
        return inflater.inflate(R.layout.file_list_fragment, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        Context context = getActivity().getBaseContext();

        mMultiWindow = MultiWindowMgr.getInstance(this.getActivity(), getProcessId());

        super.onViewCreated(view, savedInstanceState);

        if (mNavigationInfo != null) {
            mListViewImp = AbsListViewImp.createListView(mContext, view, mNavigationInfo);
            mListViewImp.addOnItemChangedListener(this);
            mListViewImp.addOnItemChangedListener(mOnItemChangedListener);
            //mListViewImp.getListView().semSetOnMultiSelectedListener(mTwMultiSelectedListener);
        }

        if (mListViewImp != null && mNavigationInfo != null) {
            mDragDrop = new DragAndDropMgr(this, mNavigationInfo.getStorageType(), mListViewImp);
            mDragDrop.attachDragListenerToView(mListViewImp.getListView());
            mListenerMgr.addListener(new DragAndDropReceiver(mContext, this, mDragDrop, ListenerMgr.LifeCycle.RESUME,
                    ListenerMgr.LifeCycle.PAUSE));

            mAdapter = new FileListAdapter(context, mNavigationInfo, this.getLoaderManager(), mListViewImp);

            if (mListViewImp.getListView() != null) {
                mListViewImp.setAdapter(mAdapter);
                mListViewImp.setOnItemClickListener(this);
                mListViewImp.setOnItemLongClickListener(this);
                setTwFluidScroll();
                setTwGoToTop();
                ActionModeType currentActionModeType = SelectionManager.getInstance(mProcessId).getActionModeType();
                if (currentActionModeType != null) {
                    setActionMode(currentActionModeType);
                }
                mListViewImp.refreshLayout();
            }
        } else {
            Log.e(this, "ListViewImp is null");
        }

        setClearHistoryButton();
        setCategorySizeView();
        setMouseKeyboardListener();
        initSoftInputMode();
    }

    protected void setMouseKeyboardListener() {
        if (mListViewImp != null) {
            MouseKeyboardMgr.setOnKeyListener(mListViewImp.getListView(), this, getStorageType());
        }
    }

    private void setTwFluidScroll() {
        boolean enabled = true;
        if (mNavigationInfo.isPickerMode()) {
            enabled = false;
        }

        mListViewImp.setFastScrollEnabled(enabled);
    }

    private void setTwGoToTop() {
        boolean enabled = true;
        if (mNavigationInfo.isPickerMode()) {
            enabled = false;
        }

        mListViewImp.twSetGoToTopEnabled(enabled);
    }

    private void updateMenuView() {
        if (isSelectActionMode() && mMenu != null) {
            if (!mListViewImp.doDeleteAnimation()) {
                mMenu.updateSelectedItemView();
            }
        } else {
            if (mActivity != null && mNavigationInfo != null && !mNavigationInfo.getIsSearchMode()) {
                mActivity.invalidateOptionsMenu();
            } else {
                UiUtils.setToggleMenuItem(mContext, mMenu, mNavigationInfo, getTotalFileCount() > 0);
            }
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        if (mActivity != null) {
            boolean isDensityChanged = UiUtils.isDensityDpiChanged(newConfig, mActivity.getDensityDpi());
            boolean isDexModeChanged = mActivity.getDesktopModeChanged();
            if (isDensityChanged && !isDexModeChanged) {
                SelectionManager.getInstance(mProcessId).savePositions(mListViewImp != null ?
                        (mListViewImp.getSelectedFilePositions()) : null);
                SelectionManager.getInstance(mProcessId).saveActionModeType(mActionModeType);
            }
        }
        super.onConfigurationChanged(newConfig);

        if (mListViewImp != null) {
            mListViewImp.onConfigurationChanged();
        }

        if (mPathIndicator != null) {
            mPathIndicator.setSplitLandMode(isSplitLandMode());
        }
        refreshCategorySizeView();
    }

    @Override
    public void onResume() {
        super.onResume();
        mListenerMgr.notifyResume();
        mMultiWindow.addStateChangeListener(this);
        mListViewImp.refreshLayout();
        refreshCategorySizeView();
    }

    @Override
    public int getListItemCount() {
        if (mAdapter != null) {
            return mAdapter.getItemCount();
        }
        return super.getListItemCount();
    }

    @Override
    public void onPause() {
        super.onPause();
        mListenerMgr.notifyPause();
        mMultiWindow.removeStateChangeListener(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        if ((mNavigationInfo != null)) {
            FileRecord record = mNavigationInfo.getCurRecord();
            if (record != null && record.getStorageType() == FileRecord.StorageType.Cloud) {
                Log.d(this, "cancel signal " + ((CloudFileRecord) record).getFileId());
                Intent intent = new Intent("com.samsung.android.slinkcloud.cancelloadfilebrowser");
                intent.putExtra("cloudid", ((CloudFileRecord) record).getFileId());
                getActivity().sendBroadcast(intent);
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mListenerMgr.notifyDestroy();
        unregisterOnItemChangedListener();
        View listView = mListViewImp.getListView();
        if (listView != null) {
            mListViewImp.setOnItemClickListener(null);
            mListViewImp.setOnItemLongClickListener(null);
            if (AppFeatures.isKnoxDesktopMode()) {
                unregisterForContextMenu(listView);
                View emptyView = mListViewImp.getEmptyView();
                if (emptyView != null) {
                    unregisterForContextMenu(emptyView);
                }
            }
        }
    }

    private NavigationInfo mPrevNavigationInfo = null;

    private boolean isItemClickValid(int position) {
        boolean bRet = true;
        if (!mListViewImp.isEnabled(position) && mListViewImp.isCheckMode()) {
            mListViewImp.setItemChecked(position, false);
            bRet = false;
        }
        return bRet;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        boolean handled = false;

        if (mAdapter == null || view == null || !isItemClickValid(position)) {
            if (mNavigationInfo != null && mNavigationInfo.isPickerMode()) {
                updateActionBarMenu();
            }
            return;
        }

        FileRecord record = mAdapter.getFileRecord(position);
        if (record != null) {
            if (UiUtils.isValidClick(view.getId()) || (mNavigationInfo != mPrevNavigationInfo)) {
                handled = _onItemClick(record);
            }
            if (handled) {
                mPrevNavigationInfo = mNavigationInfo;
            } else {
                if (mNavigationInfo.isPickerMode() && (mListViewImp.getCheckedItemCount() > mNavigationInfo.getMaxSelectCnt())) {
                    showMaxSelectedFilesToast();
                    mListViewImp.setItemChecked(position, false);
                }
                if (UiUtils.isTalkBackEnabled(mContext)) {
                    mAdapter.changeContentDescription(view, mListViewImp.isItemChecked(position));
                }
                if ((getActionModeType() == ActionModeType.SELECT_SHARE_FILE_OPERATION) && (!UiUtils.isShareAvailable(mContext, record))) {
                    mListViewImp.setItemChecked(position, false);
                } else {
                    mListViewImp.notifyItemChecked();
                    MouseKeyboardMgr.setFocusedListIndexForMouse(position);
                }
            }
        }
    }

    protected boolean _onItemClick(FileRecord record) {
        Log.a(this, "_onItemClick : " + record.getName());
        boolean ret = false;
        if (record.isDirectory()) {
            if (!isSelectActionMode() || mNavigationInfo.isPickerMode()) {
                SamsungAnalyticsLog.sendLog(mProcessId, SamsungAnalyticsLog.Event.FOLDER_OPEN, "Folder", null);
                MyFilesFacade.executeRecord(mProcessId, getActivity(), record);
                ret = true;
            }
        } else {
            if (mActionModeType == ActionModeType.NORMAL) {
                if (!mNavigationInfo.isPickerMode() && !mNavigationInfo.isSelectDestination() && !mNavigationInfo.isCreateDocument()) {
                    String detail = record.getExt().isEmpty() ? "No extension" : record.getExt();
                    SamsungAnalyticsLog.sendLog(mProcessId, SamsungAnalyticsLog.Event.FILE_OPEN, detail, null);
                    MyFilesFacade.executeRecord(mProcessId, getActivity(), record);
                    ret = true;
                } else if (record instanceof LocalFileRecord && record.getPath() == null
                        && record.getName().equals(mContext.getResources().getString(R.string.create_folder))) {
                    SamsungAnalyticsLog.sendLog(mProcessId, SamsungAnalyticsLog.Event.CREATE_FOLDER, null);
                    MyFilesFacade.createDir(mProcessId, mContext, this, mNavigationInfo.getCurRecord());
                    ret = true;
                } else if (record instanceof CloudFileRecord && ((CloudFileRecord) record).getFileId() == null
                        && record.getName().equals(mContext.getResources().getString(R.string.create_folder))) {
                    MyFilesFacade.createDir(mProcessId, mContext, this, mNavigationInfo.getCurRecord());
                }
            }
        }
        return ret;
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        Log.a(this, "onItemLongClick " + position);
        boolean bRet = true;

        if (isResumed()) {
            bRet = _onItemLongClick(view, position);
        }
        return bRet;
    }

    protected boolean _onItemLongClick(View view, int position) {
        Log.d(this, "_onItemLongClick");
        if (mAdapter == null) {
            Log.e(this, "Adapter is null");
            return false;
        }

        boolean ret = true;

        if (mNavigationInfo.getIsSearchMode()
                && (mActivity != null && mActivity.getSearchView() != null)) {
            mActivity.getSearchView().collapseSearchMenu();
        }

        if (!mAdapter.isCheckMode()) {
            if (NavigationManager.isPossibleToActionMode()) {
                if (!isSelectActionMode() && !mNavigationInfo.isPickerMode()
                        && !mNavigationInfo.isSelectDestination() && !mNavigationInfo.isCreateDocument()) {
                    SamsungAnalyticsLog.sendLog(mProcessId, SamsungAnalyticsLog.Event.LONG_PRESS, mAdapter.getFileRecord(position).isDirectory() ? "Folder" : "File", SamsungAnalyticsLog.SelectMode.NORMAL);
                    MyFilesFacade.toSelectMode(getProcessId(), this, mListViewImp, position, ToSelectModeCmd.SelectModeType.SELECT_MODE);
                    MouseKeyboardMgr.setFocusedListIndexForMouse(position);
                }
            } else {
                Toast.makeText(getActivity(), R.string.cant_perform_action, Toast.LENGTH_LONG).show();
            }
        } else {
            if (mListViewImp.isItemChecked(position) && mDragDrop.supportDragAndDrop(this)) {
                if (NavigationManager.isPossibleToActionMode(mProcessId)) {
                    mDragDrop.startDrag(view, getSelectedFile(), mAdapter.getFileRecord(position));
                    if (!AppFeatures.isKnoxDesktopMode()) {
                        // to block the haptic feedback
                        // in dex mode, haptic feedback is disabled (cannot enable).
                        ret = false;
                    }
                } else {
                    Toast.makeText(getActivity(), R.string.cant_perform_action, Toast.LENGTH_LONG).show();
                }
            }
        }
        return ret;
    }

    @Override
    public void setActionMode(ActionModeType actionMode) {
        super.setActionMode(actionMode);

        boolean bShowCheckBox = false;
        boolean isShare = false;
        boolean isPicker = false;
        boolean needToCheckSelection = false;

        switch (actionMode) {
            case SELECT_FILE_FOLDER_OPERATION:
                bShowCheckBox = true;
                mListViewImp.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
                break;
            case EDIT_FILE_FOLDER_OPERATION:
                needToCheckSelection = true;
                bShowCheckBox = true;
                mListViewImp.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
                break;
            case SELECT_SHARE_FILE_OPERATION:
                needToCheckSelection = true;
                bShowCheckBox = true;
                isShare = true;
                mListViewImp.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
                break;
            default:
                break;
        }
        if (mNavigationInfo != null) {
            switch (mNavigationInfo.getNavigationMode()) {
                case Pick_one_file:
                    mListViewImp.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
                    needToCheckSelection = true;
                    bShowCheckBox = true;
                    isPicker = true;
                    break;
                case Pick_files:
                    needToCheckSelection = true;
                    isPicker = true;
                    mListViewImp.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
                    bShowCheckBox = true;
                    break;
                case Optimize_storage_files:
                case Preview_compress_item:
                    mListViewImp.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
                    bShowCheckBox = true;
                    break;
                default:
                    break;
            }

            if (!bShowCheckBox) {
                mListViewImp.setChoiceMode(ListView.CHOICE_MODE_NONE);
            }

            invalidateView(bShowCheckBox, isShare, isPicker);

            if (mIsNeedRefreshViewAs) {
                mIsNeedRefreshViewAs = false;
                View view = getView();
                if (view != null) {
                    view.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            NavigationManager.getInstance(getProcessId()).refreshNotify();
                        }
                    }, 500);
                }
            }

            if (needToCheckSelection) {
                setDefaultSelection();
            }
        }
    }

    protected void setDefaultSelection() {
        int totalCheckableFileCount = getTotalCheckableFileCount();

        if (totalCheckableFileCount == 1) {
            selectItems(getTotalFileCount());
        } else if (totalCheckableFileCount == 0) {
            mListViewImp.notifyItemChecked();
        }
    }

    private void invalidateView(boolean bShowCheckBox, boolean isShare, boolean isPicker) {
        Activity activity = getActivity();
        if (activity != null) {
            View mActionbar = activity.findViewById(R.id.action_select);
            mListViewImp.setCheckMode(bShowCheckBox, mActionbar, isShare, isPicker);
            mListViewImp.invalidateViews();
        }
    }

    public void reload() {
        Log.d(this, "reload this= " + this);
        View view = getView();
        if (view != null) {
            view.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mAdapter.reload();
                }
            }, 100);
        }
    }

    @Override
    public FileRecord getFileRecord(int position) {
        return mAdapter.getFileRecord(position);
    }

    public ArrayList<FileRecord> getSelectedFile() {
        if (mListViewImp != null) {
            return mListViewImp.getSelectedFile();
        }
        return null;
    }

    @Override
    public int getSelectedFileCount() {
        int nRet = 0;
        if (mListViewImp != null) {
            nRet = mListViewImp.getCheckedItemCount();

            if (nRet == 0 && mListViewImp.getAdapter() != null && !mListViewImp.getAdapter().getLoadFinished()) {
                nRet = -1;
            }

            if (nRet != -1 && mListViewImp.isSelectAll()) {
                nRet = getTotalCheckableFileCount() - nRet;
            }
        }

        return nRet;
    }

    @Override
    public int getTotalFileCount() {
        return mListViewImp == null ? 0 : mListViewImp.getCount();
    }

    @Override
    public int getTotalCheckableFileCount() {
        int validItemCount = 0;
        if (mListViewImp != null) {
            for (int i = 0; i < mListViewImp.getCount(); i++) {
                if (mAdapter != null && mAdapter.isCheckable(i)) {
                    validItemCount++;
                }
            }
        }

        return validItemCount;
    }

    @Override
    public void selectAll(boolean select) {
        if (mNavigationInfo != null) {
            int maxSelectCount = mNavigationInfo.getMaxSelectCnt();
            if (select && mNavigationInfo.isPickerMode() && (maxSelectCount < getTotalCheckableFileCount())) {
                selectItems(maxSelectCount);
                showMaxSelectedFilesToast();
            } else {
                mListViewImp.selectAll(select);
                mListViewImp.invalidateViews();
            }
            if (select) {
                boolean isSelectMode = mNavigationInfo.isSelectMode();
                if (isSelectMode && mNavigationInfo.getNavigationMode() == NavigationInfo.NavigationMode.Pick_files) {
                    SamsungAnalyticsLog.sendLog(SamsungAnalyticsLog.ScreenPath.FROM_OTHER, SamsungAnalyticsLog.Event.SELECT_ALL, SamsungAnalyticsLog.SelectMode.SELECTION_MODE);
                } else {
                    FileRecord curRecord = getNavigationInfo().getCurRecord();
                    if (curRecord != null) {
                        SamsungAnalyticsLog.SelectMode selectMode = (UiUtils.isCategoryFolderList(curRecord)) ?
                                SamsungAnalyticsLog.SelectMode.SELECTION_CATEGORY_FOLDER_MODE : SamsungAnalyticsLog.SelectMode.SELECTION_MODE;
                        SamsungAnalyticsLog.sendLog(mProcessId, SamsungAnalyticsLog.Event.SELECT_ALL, selectMode);
                    }
                }
            }
        } else {
            Log.e(this, "selectAll() - NavigationInfo is null");
        }
    }

    private void selectItems(int count) {
        int checkedItemCount = mListViewImp.getCheckedItemCount();

        if (checkedItemCount < count) {
            for (int i = 0; i < mListViewImp.getCount(); i++) {
                if (!mListViewImp.isItemChecked(i) && mAdapter != null && mAdapter.isCheckable(i)) {
                    mListViewImp.setItemChecked(i, true);
                    checkedItemCount++;
                    if (checkedItemCount == count) {
                        break;
                    }
                }
            }
        }
    }

    @Override
    public void setEmptyView() {
        if (mPathIndicator != null) {
            mPathIndicator.updateFocusForKeyboard();
        }

        ViewGroup root = (ViewGroup) getView();
        if (root == null) {
            Log.e(this, "root view is null");
            return;
        }

        View emptyView = _setEmptyView(root);

        if (emptyView != null) {
            ensureEmptyView(emptyView);
            mLoadingStatus = false;
            mListViewImp.setEmptyView(emptyView);
            mDragDrop.attachDragListenerToView(emptyView);
            if (AppFeatures.isKnoxDesktopMode()) {
                mListViewImp.getEmptyView().setOnKeyListener(new View.OnKeyListener() {
                    @Override
                    public boolean onKey(View v, int keyCode, KeyEvent event) {
                        return false;
                    }
                });
                emptyView.requestFocus();
            }
        }
    }

    protected View _setEmptyView(ViewGroup root) {
        ViewStub emptyViewStub = (ViewStub) root.findViewById(R.id.empty_view_stub);
        View emptyView;

        if (emptyViewStub != null) {
            emptyView = emptyViewStub.inflate();

        } else {
            emptyView = root.findViewById(R.id.empty_view);
        }
        return emptyView;
    }

    protected void ensureEmptyView(View emptyView) {
        int mainTextId = mAdapter.getEmptyTextId();
        int subTextId = mAdapter.getEmptySubTextId();
        int iconId = mAdapter.getEmptyIconId();
        emptyView.setFocusable(false);
        setEmptyText(emptyView, mainTextId, subTextId, iconId);
    }

    private void setEmptyText(View emptyView, int mainTextId, int subTextId, int iconId) {
        View textContainer = emptyView.findViewById(R.id.no_item_text_container);
        TextView subTextView = null;
        if (subTextId != AppConstants.UNDEFINED) {
            subTextView = (TextView) textContainer.findViewById(R.id.no_item_sub_text);
            subTextView.setText(subTextId);
            subTextView.setVisibility(View.VISIBLE);
        }

        TextView mainTextView = (TextView) textContainer.findViewById(R.id.no_item_text);
        mainTextView.setText(mainTextId);
        textContainer.setContentDescription(getString(mainTextId));
        mainTextView.setTextColor(mAdapter.getEmptyTextColor());
        PathLineAnimationView pathLineAnimationView = (PathLineAnimationView) textContainer.findViewById(R.id.no_item_icon);
        if (iconId != AppConstants.UNDEFINED) {
            pathLineAnimationView.setVisibility(View.VISIBLE);
            if (mListViewImp.getEmptyView() == null || mLoadingStatus) {
                ViEffectMgr.getInstance().setEmptyViewAnimation(mContext, pathLineAnimationView, mainTextView, subTextView, iconId);
            }
        } else {
            pathLineAnimationView.setVisibility(View.GONE);
        }
    }

    @Override
    public void clearEmptyView() {
        if (mListViewImp != null) {
            mListViewImp.setEmptyView(null);
            mLoadingStatus = false;
        }
    }

    @Override
    public void setLoadingView() {
        ViewGroup root = (ViewGroup) getView();
        if (root == null) {
            Log.e(this, "root view is null");
            return;
        }

        ViewStub loadingViewStub = (ViewStub) root.findViewById(R.id.loading_view_stub);
        View loadingView;

        if (loadingViewStub != null) {
            loadingView = loadingViewStub.inflate();
        } else {
            loadingView = root.findViewById(R.id.loading_view);
        }

        if (loadingView != null) {
            mLoadingStatus = true;
            mNeedUpdateAfterLoading = true;
            mListViewImp.setEmptyView(loadingView);
        }
    }

    @Override
    public AbsListView getListView() {
        return (mListViewImp == null) ? null : mListViewImp.getListView();
    }

    @Override
    public void setPathIndicator(PathIndicator pathIndicator) {
        if (pathIndicator != null && mNavigationInfo != null) {
            pathIndicator.setFragment(this);
            AbsMyFilesFragment curFragment = mNavigationInfo.getCurFragment();
            if ((curFragment != null) && curFragment.hasSubTitle()) {
                pathIndicator.setVisibility(View.GONE);
            } else if (!AppFeatures.isTabletUIMode() && getStorageType() == FileRecord.StorageType.Recent) {
                pathIndicator.setVisibility(View.GONE);
            } else if (getStorageType() == FileRecord.StorageType.Blank) {
                pathIndicator.setVisibility(View.GONE);
            } else {
                pathIndicator.setVisibility(View.VISIBLE);
            }

            pathIndicator.updatePathIndicator(mNavigationInfo);

            mPathIndicator = pathIndicator;
            mPathIndicator.setSplitLandMode(isSplitLandMode());
        }
    }

    @Override
    public boolean getLoadingStatus() {
        return mLoadingStatus;
    }

    public int getCurListPosition() {
        int nRet = 0;
        if (mListViewImp != null) {
            nRet = mListViewImp.getPosition();
        }
        return nRet;
    }

    @Override
    public void onMediaMounted(String path) {
        StorageMonitor.updateSubSystemStorageState(mContext);
        NavigationInfo curInfo = getNavigationInfo();
        FileRecord curRec = curInfo.getCurRecord();

        if (curRec.getStorageType() == FileRecord.StorageType.Category) {
            if (StorageMonitor.isSdCardPath(path) || FileUtils.isPrivateFolder(path)) {
                closePopupDialog();
                finishActionMode();
            }
        }
    }

    private boolean needRefreshOnMediaUnmounted(String path, FileRecord record) {
        boolean ret = false;
        if (record.getStorageType() == FileRecord.StorageType.Recent) {
            ret = true;
        } else if (record.getStorageType() == FileRecord.StorageType.Category) {
            if (StorageMonitor.isRemovedExtSDCard(path) || FileUtils.isPrivateFolder(path)) {
                ret = true;
            }
        }
        return ret;
    }

    @Override
    public void onMediaEject(String path) {
        StorageMonitor.updateSubSystemStorageState(mContext);
        Bundle extras = new Bundle();
        extras.putString(AbsReloadStrategyImp.EXTRA_KEY_PATH, path);

        NavigationInfo curInfo = getNavigationInfo();
        FileRecord curRec = curInfo.getCurRecord();

        if (curRec != null) {
            String curPath = curRec.getFullPath();
            if (path != null) {
                if (curPath == null || curPath.startsWith(path)) {
                    if (!curInfo.isPickerMode() && !curInfo.isSelectOpDestination()) {
                        ViEffectMgr.getInstance().fileSelectedBoxEffect(getSelectedFileBox(), false);
                        curInfo.setNavigationMode(NavigationInfo.NavigationMode.Normal);
                    }
                    MyFilesFacade.goHome(getProcessId(), curInfo, mContext);
                } else if (needRefreshOnMediaUnmounted(path, curRec)) {
                    performReloadStrategy(AbsReloadStrategyImp.ReloadCause.MediaUnmounted, extras, 0);
                    closePopupDialog();
                    finishActionMode();
                }
            }
        }
    }

    @Override
    public void onMediaScanStart() {
        performReloadStrategy(AbsReloadStrategyImp.ReloadCause.MediaScanStarted, null, 0);
    }

    @Override
    public void onMediaScanFinish() {
        performReloadStrategy(AbsReloadStrategyImp.ReloadCause.MediaScanFinished, null, 0);
        updateMenuView();

        if (mNavigationInfo != null && mNavigationInfo.isPickerMode() && mListViewImp != null) {
            mListViewImp.selectAll(false);
        }
    }

    @Override
    protected void _onContentChanged(int event) {
        performReloadStrategy(AbsReloadStrategyImp.ReloadCause.ContentChanged, null, event);
    }

    private void performReloadStrategy(AbsReloadStrategyImp.ReloadCause cause, Bundle extras, int event) {
        if (mReloadStrategy != null) {
            mNeedUpdateAfterLoading = true;
            mReloadStrategy.reload(cause, extras, event);
        }
    }

    @Override
    public void onLoadFinished() {
        if (!mIsNeedRefreshViewAs) {
            closePopupDialog();
        }
        if (mAdapter != null) {
            mAdapter.clearPreValue();
            if (mNeedUpdateAfterLoading && getStorageType() != FileRecord.StorageType.Downloads && getStorageType() != FileRecord.StorageType.OptimizeStorage) {
                mAdapter.reload();
            }
        }

        if (mListViewImp != null) {
            mListViewImp.clearPreValue();
            if (!mListViewImp.doDeleteAnimation()) {
                if (mAdapter != null && mAdapter.isCheckMode()) {
                    if (mPreItemCnt >= 0 && mPreItemCnt != mListViewImp.getCount()) {
                        mListViewImp.clearChoices();
                        finishActionMode();
                    } else {
                        if (mMenu != null) {
                            updateActionBarMenu();
                        }
                    }
                }
            }
            mPreItemCnt = mListViewImp.getCount();
        }

        updateMenuView();

        if (mNavigationInfo != null) {
            if (getStorageType() != FileRecord.StorageType.Downloads
                    && (mNeedUpdateAfterLoading || mNavigationInfo.needUpdateOptionsMenuAfterLoad())) {
                mNeedUpdateAfterLoading = false;
            }

            ToSelectModeCmd.SelectModeType startWithSelectMode = mNavigationInfo.getStartWithSelectMode();
            if (startWithSelectMode != null) {
                int pos = mNavigationInfo.getStartSelectionPos();
                mNavigationInfo.setStartWithSelectMode(null);
                MyFilesFacade.toSelectMode(getProcessId(), this, mListViewImp, pos, startWithSelectMode);
            }
        }
        notifyOnItemLoadFinished();

        setCategoryFileSize();

        if (mNavigationInfo != null && mContext != null) {
            BixbyUtil.sendResponse(mContext, mNavigationInfo.getCurRecord(), mLoadingStatus);
        }

        if (mNavigationInfo != null && mNavigationInfo.isPickerMode()) {
            setDefaultSelection();
        }
        if (mActivity != null && !mActivity.getDesktopModeChanged()) {
            mListViewImp.setItemsChecked(SelectionManager.getInstance(mProcessId).getSelectedPositions());
            SelectionManager.getInstance(mProcessId).clear();
        }
    }

    private boolean isItemDragValid(int position) {
        boolean bRet = true;
        FileRecord record = mAdapter.getFileRecord(position);

        if (mNavigationInfo != null && mNavigationInfo.isPickerMode() && record != null && record.isDirectory()) {
            mListViewImp.setItemChecked(position, false);
            bRet = false;
        }

        return bRet;
    }

    private View getSelectedFileBox() {
        View fileSelectedContainer = getActivity().findViewById(R.id.file_selected_container);
        View fileSelectedLayout;

        if (fileSelectedContainer instanceof ViewStub) {
            fileSelectedLayout = ((ViewStub) fileSelectedContainer).inflate();
        } else {
            fileSelectedLayout = fileSelectedContainer;
        }
        return fileSelectedLayout;
    }

    public int getViewType() {
        int ret = -1;
        if (mListViewImp != null) {
            ret = mListViewImp.getViewType();
        }
        return ret;
    }

    public void setDeleteItemEffect() {
        mListViewImp.setDeleteAnimation();
    }

    private boolean isSplitLandMode() {
        return !mNavigationInfo.isLeftPanelDisabled() &&
                mMultiWindow.getWindowState() == MultiWindowMgr.WindowState.LANDSCAPE;
    }

    @Override
    public void onTimeSetChanged() {
        mListViewImp.invalidateViews();
        UiUtils.clearCachedTime();
    }

    @Override
    public void onModeChanged() {
        if (mPathIndicator != null) {
            mPathIndicator.setSplitLandMode(isSplitLandMode());
        }
    }

    @Override
    public void onZoneChanged() {

    }

    @Override
    public void onSizeChanged(Rect rectInfo) {

    }

    @Override
    public void clearListViewPreValue() {
        if (mListViewImp != null) {
            mListViewImp.clearPreValue();
        }
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        if (mMenu != null) {
            int pos = getTouchPosition();
            FileRecord record;
            if (pos > -1) {
                record = mAdapter.getFileRecord(pos);
            } else {
                record = mNavigationInfo.getCurRecord();
            }
            if (record != null) {
                setPanelInfo(AppConstants.PanelInfo.RightPanel);
                mMenu.onCreateContextualMenu(menu, this, record);
            }
        }
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        if (mMenu != null && item != null) {
            int pos = getTouchPosition();

            FileRecord record;
            if (pos > -1) {
                record = mListViewImp.getFileRecord(pos);
            } else {
                record = mNavigationInfo.getCurRecord();
            }
            if (record != null) {
                setPanelInfo(AppConstants.PanelInfo.None);
                mMenu.onContextualItemSelected(item, this, record);
            }
        }
        return false;
    }

    public void registerOnItemChangedListener(OnItemChangedListener listener) {
        mOnItemChangedListener = listener;
    }

    private void unregisterOnItemChangedListener() {
        mListViewImp.removeOnCheckedItemChangedListener(this);
        if (mOnItemChangedListener != null) {
            mListViewImp.removeOnCheckedItemChangedListener(mOnItemChangedListener);
            mOnItemChangedListener = null;
        }
    }

    private void notifyOnItemLoadFinished() {
        if (mOnItemChangedListener != null) {
            mOnItemChangedListener.onItemLoadFinished();
        }
    }

    public void notifyOnItemUpdated() {
        if (mOnItemChangedListener != null) {
            mOnItemChangedListener.onItemUpdated();
        }
    }

    @Override
    public void onCheckedItemChanged() {
        updateActionBarMenu();
    }

    @Override
    public void onItemLoadFinished() {
    }

    @Override
    public void onItemUpdated() {
    }

    protected void setClearHistoryButton() {
        mClearHistoryButton = getActivity().findViewById(R.id.clear_history_button);
        if (mClearHistoryButton != null) {
            mClearHistoryButton.setVisibility(View.GONE);
        }
    }

    private void refreshCategorySizeView() {
        if (mCategorySizeView != null) {
            mCategorySizeView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
                    mContext.getResources().getDimensionPixelSize(R.dimen.navigation_view_item_text_size));
        }
    }

    private void setCategorySizeView() {
        mCategorySizeView = (TextView) getActivity().findViewById(R.id.path_indicator_size);
        if (mCategorySizeView != null && mNavigationInfo != null) {
            if (UiUtils.isCategoryFolderList(mNavigationInfo.getCurRecord())) {
                mCategorySizeView.setText("");
                mCategorySizeView.setVisibility(View.VISIBLE);
                mCategorySizeView.setFocusable(false);
            } else {
                mCategorySizeView.setVisibility(View.GONE);
            }
        }
    }

    private void setCategoryFileSize() {
        if (mCategorySizeView != null && mNavigationInfo != null && UiUtils.isCategoryFolderList(mNavigationInfo.getCurRecord())) {
            long totalFileSize = getTotalFileSize();
            String formatSize = Formatter.formatFileSize(mContext, totalFileSize);
            mCategorySizeView.setText(formatSize);

            if (totalFileSize < SIZE_KILOBYTE) {
                formatSize = totalFileSize + " " + mContext.getResources().getString(R.string.bytes_tts);
            }
            mCategorySizeView.setContentDescription(formatSize);
        }
    }

    @Override
    public void onMediaUnmounted(String path) {
        FileRecord record = mNavigationInfo.getCurRecord();
        if (!record.exists(mContext)) {
            if (StorageMonitor.isRemovedExtSDCard(record.getFullPath())) {
                MyFilesFacade.goHome(getProcessId(), mNavigationInfo, mContext);
            }
        }
    }

    @Override
    public void onSplitBarPressed() {
        if (mListViewImp != null && AppFeatures.isKnoxDesktopMode()) {
            mListViewImp.onSplitBarPressed();
        }
        if (mMenu != null) {
            if (isSelectActionMode() || (mNavigationInfo != null && mNavigationInfo.isSelectMode())) {
                mMenu.updateSelectAllDivider(true);
            }
            mMenu.updateSelectAllStartMargin();
        }
    }

    @Override
    public void onSplitBarReleased() {
        if (mListViewImp != null && AppFeatures.isKnoxDesktopMode()) {
            mListViewImp.onSplitBarReleased();
        }
        if (mMenu != null) {
            if (isSelectActionMode() || (mNavigationInfo != null && mNavigationInfo.isSelectMode())) {
                mMenu.updateSelectAllDivider(false);
            }
            mMenu.updateSelectAllStartMargin();
        }
    }

    @Override
    public void onSplitBarMoved() {
        if (mMenu != null && (isSelectActionMode() || (mNavigationInfo != null && mNavigationInfo.isSelectMode()))) {
            mMenu.updateSelectAllStartMargin();
        }
    }

    public FileListAdapter getAdapter() {
        return mAdapter;
    }

    public void stopPinchZoomWorking() {
        mListViewImp.stopPinchZoomWorking();
    }

    private void initSoftInputMode() {
        if (mActivity != null) {
            int softInputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;

            if (getStorageType() == FileRecord.StorageType.Blank || mActivity instanceof FolderSelectorBottomSheetActivity) {
                softInputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING;
            }

            Window window = mActivity.getWindow();
            window.setSoftInputMode(softInputMode);
        }
    }
}
